package com.mlnx.yingbaisui.device.leida;

import com.mlnx.common.utils.MyLog;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.shan.iot.protocol.ReqRepMsg;
import org.shan.iot.server.codec.HLCDecoder;
import org.shan.iot.utils.ByteUtils;

/**
 * Created by amanda.shan on 2023/3/2.
 */
public class TestHLCDecoder extends HLCDecoder {

    private MyLog log = MyLog.getLog(this.getClass());

    static byte[] HEADS = {0x55, (byte) 0xaa};

    private int cmd;

    public TestHLCDecoder() {
        super(HEADS);
    }

    @Override
    public ReqRepMsg getReqRepMsg(ByteBuf in, int len) {

        ReqRepMsg reqRepMsg = new TestReqRepMsg();
        reqRepMsg.decode(in, len);

        return reqRepMsg;
    }


    @Override
    public ReqRepMsg decode(ChannelHandlerContext ctx, ByteBuf buf) {
        switch (state) {
            case HEAD:
//                log.debug("匹配head");
                if (matchHead(buf)) {
                    state = State.LEN;
                } else {
                    break;
                }
            case LEN:
                if (buf.isReadable(lenSize)) {
                    byte[] bs = new byte[lenSize];
                    buf.readBytes(bs);
                    cmd = bs[0];
                    len = bs[1];
                    state = State.CONTANT;
//                    log.debug("收到len:{}", len);
                } else {
                    break;
                }
            case CONTANT:
                if (buf.isReadable(len+2)) {
//                    log.debug("recive  contant:{}", ByteBufUtil.hexDump(buf));
                    try {
                        ByteBuf frame = null;
                        try {
                            frame = buf.readBytes(len);
                            ReqRepMsg reqRepMsg = getReqRepMsg(frame, len);
                            return reqRepMsg;
                        } finally {
                            ReferenceCountUtil.release(frame);
                        }

                    } catch (Exception e) {
                        log.error(e, e.getMessage());
                    } finally {
                        state = State.HEAD;
                    }
                } else {
                    return null;
                }
                break;
            default:
        }

        return null;
    }
}
